#!/usr/bin/python
#coding=utf-8
from sqlalchemy.types import VARCHAR, DECIMAL
import pandas as pd
import datetime
from common import df_operator as op, db_utils as util
import sys

dtypedict = {'COST_CENTER': VARCHAR,'UNIT_CODE': VARCHAR,'CLASS': VARCHAR,
            'SHIFT': VARCHAR,'DATE': VARCHAR,'PRODUCE_START_TIME': VARCHAR,'PRODUCE_END_TIME': VARCHAR,
            'IND': VARCHAR,'IND_NAME': VARCHAR,'IND_UNIT': VARCHAR,
            'INDEX_VALUE': DECIMAL,'DATA_TYPE': VARCHAR,
            'REC_CREATOR': VARCHAR, 'REC_CREATE_TIME': VARCHAR, 'REC_REVISOR': VARCHAR,'REC_REVISOR_TIME': VARCHAR
            }

def main(cost_center,unit_code,work_time):
    work_time_str = work_time.strftime("%Y%m%tmp_dict%H%M%S")
    if len(work_time_str) == 14:
        if work_time_str[8:10] >= '08' and work_time_str[8:10] < '20':
            start_time = work_time_str[0:8]+"080000"
            end_time = work_time_str[0:8]+"200000"
        elif work_time_str[8:10] >= '20':
            start_time = work_time_str[0:8] + "200000"
            end_time = (work_time + datetime.timedelta(days=1)).strftime("%Y%m%tmp_dict") + "200000"
        elif work_time_str[8:10] < '08':
            start_time = (work_time - datetime.timedelta(days=1)).strftime("%Y%m%tmp_dict") + "200000"
            end_time = work_time_str[0:8] + "080000"
    elif len(work_time_str) == 6:
        start_time = datetime.strptime(work_time_str[0:5] + "01",'%Y%m%tmp_dict')#先转成当月
        start_time = (start_time - datetime.timedelta(hours=1)).strftime("%Y%m%tmp_dict") + "200000" #前一天晚上20点
        end_time = work_time_str[0:5] + "31200000" #当月最后一天
    elif len(work_time_str) == 4:
        start_time = (datetime.strptime(work_time_str[0:3] , '%Y') - datetime.timedelta(years=1)).strftime("%Y")+'1231200000'
        end_time = work_time_str[0:3] +  '1231200000'

    #先删除这段时间的数据
    if len(work_time_str) == 14:
       del_sql = """delete from BGTARSSI00.T_ADS_FACT_SICB_MO0201 WHERE COST_CENTER='MIDE' and UNIT_CODE = 'Q518'and DATA_TYPE = '0' and PRODUCE_START_TIME = '""" + str(start_time) + """' AND PRODUCE_END_TIME = '""" + str(end_time) + """'"""
    else:
        del_sql = """delete from BGTARSSI00.T_ADS_FACT_SICB_MO0201 WHERE COST_CENTER='MIDE' and UNIT_CODE = 'Q518'and DATA_TYPE = '0' and PRODUCE_START_TIME = '""" + str(
            start_time) + """' AND PRODUCE_END_TIME = '""" + str(end_time) + """' and DATE = '"""+ work_time_str +"""'"""
    conn_rds.execute(del_sql)

    query_sql = """select IND,CALC_LOGIC as sql_m,DATA_SOURCE_1 from BGTARSSI00.T_ADS_WH_SICB_MO0201A WHERE  UNIT_CODE =  '"""+ unit_code +"""'  ORDER BY SEQ"""
    df = pd.read_sql(query_sql, conn_rds)
    for tup in zip(df['ind'], df['sql_m'], df['data_source_1']):
        sql_m = op.replaceColumn(str(tup[1]), ["P_DATA_TYPE", "P_UNIT", "P_COST_CENTER",  "P_START_TIME", "P_END_TIME", "P_WORK_TIME", "P_WORK_TIME"],
                                       ["0", unit_code,cost_center,start_time,end_time,work_time_str,work_time_str])
        # print(sql_m)
        df_fact = util.query(conn=conn_rds if tup[2] == "RDS" else conn_db2, sql=sql_m)
        util.insert(df_fact, conn_rds, "T_ADS_FACT_SICB_MO0201", "BGTARSSI00", dtypedict)

if __name__ == '__main__':
    '''先读配置表
      再获取RDS连接
    '''
    now_time = datetime.datetime.now() - datetime.timedelta(hours=9)
    if len(sys.argv)>1:
        now_time = sys.argv[1]
    # start_time = '20210321200000'
    # end_time = '20210322200000'
    global conn_db2, conn_rds
    conn_rds = util.getConnectionDb2('10.70.48.121', '50000 ', 'RG0PROD', 'bgtaroq000', 'bgtaroq000bgta')
    conn_db2 = util.getConnectionDb2('10.70.16.170', '50170 ', 'dbprode7', 'dbprode7', 'dbprode7')

    days_n = 31
    while(days_n>0):
        use_time = now_time - datetime.timedelta(days=days_n)
        main("MIDE", "Q518", use_time)
        print(days_n)
        days_n = days_n - 1
    conn_rds.close()
    conn_db2.close()

    sys.exit()